let express = require('express');
let router = express.Router();
let fs = require('fs');
let UUID = require('uuid');
let {transformArray} = require('../utils/index');
let {listPath, usersPath} = require('../utils/pathManager');

router.get('/list', function (req, res) {
  let articleList = fs.readFileSync(listPath, 'utf-8');
  articleList = transformArray(articleList);
  res.send({
    code: 1,
    msg: '文章列表',
    data: articleList
  });
});
router.get('/detail', function (req, res) {

  let {id} = req.query;
  let articleList = fs.readFileSync(listPath, 'utf-8');
  articleList = transformArray(articleList);
  let item = articleList.find(item => item.articleId === id);
  res.send({
    code: 1,
    msg: '文章详情',
    data: item
  });
});
router.get('/type', function (req, res) {
  res.send({
    code: 1,
    msg: '文章分类',
    data: [
      '新闻类',
      '娱乐类'
    ]
  });
});
router.post('/publish', function (req, res) {
  let title = req.body.title;
  let summary = req.body.summary;
  let content = req.body.content;
  let type = req.body.type;
  let username = req.body.username;
  let avatar = req.body.avatar;
  let uid = req.body.uid;

  console.log(title,
    summary,
    content,
    type,
    username,
    avatar,
    uid);

  //校验字段
  if (!title || !content || !username || !avatar || !uid) {
    res.status(422).send({
      code: 0,
      error: '发布失败, 必须要有字段 title/content/username/avatar/uid'
    });
    return
  }

  //发布 传过来的数据 存储到list.json

  let articleList = fs.readFileSync(listPath, 'utf-8');
  let userList = fs.readFileSync(usersPath, 'utf-8');

  articleList = transformArray(articleList);
  userList = transformArray(userList);

  //判断有没有这个人 没有 返回400  有 再往下走
  let index = userList.findIndex(item => item.uid === uid);
  if (index === -1) {
    res.status(400).send({
      code: 0,
      error: '没有此用户'
    });
    return
  }

  //存储数据
  articleList.push({
    title,
    summary: summary || '摘要啊',
    content,
    type: type || '默认类型',
    username,
    avatar,
    uid,
    createDate: new Date().toLocaleDateString()+' '+new Date().toLocaleTimeString(),
    articleId: UUID.v1()
  });
  fs.writeFileSync(listPath, JSON.stringify(articleList), 'utf-8');
  res.send({
    code: 1,
    msg: '发布成功'
  });
});

module.exports = router;
